#include <iostream>
#include <memory>
#include <unistd.h>
#include <cstdio>
#include "server.hpp"
#include "err.hpp"

void Usage()
{
    std::cout << "Please enter the correct format: "
              << "./server [port]" << std::endl;
}

void LowerToUpper(void *ptr)
{
    char *p = static_cast<char *>(ptr);
    while (*p)
    {
        if (islower(*p))
        {
            *p = toupper(*p);
        }
        ++p;
    }
}

std::string ExecuteCommand(const std::string& command)
{

    FILE *fp = popen(command.c_str(), "r");

    // 读取文件中指令的输出内容
    char s_buf[1024];
    std::string ret;
    char* s;

    while (s = fgets(s_buf, sizeof(s_buf), fp))
    {
        ret += s;
    }

    pclose(fp);

    return ret;
}

std::string EchoService(const std::string& msg)
{
    return msg;
}

// ./server [port] (port为该网络进程的端口号)
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage();
        exit(USAGE_ERR);
    }

    std::unique_ptr<UdpServer> us_ptr(new UdpServer(atoi(argv[1]), ExecuteCommand));

    us_ptr->Initial();
    
    us_ptr->Start();

    return 0;
}